package com.wuqi.dev.exceptiondemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.File;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = (ImageView) findViewById(R.id.image_view);
        String imgPath = "/storage/sdcard/dcim/camera/img_20170315_204412.jpg";
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        printBmpInfo(bitmap);


        // RGB565
        // 8888


        // 图片的质量压缩
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 0, baos);
//        byte[] bytes = baos.toByteArray();
//        Log.d("MainActivity", "bytes.length:" + bytes.length);
//        Bitmap out = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//        Log.d("MainActivity", "图片的大小: " + (out.getByteCount()/1024f/1024f));

        // 采样率
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap out = BitmapFactory.decodeFile(imgPath, options);
        printBmpInfo(out);

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
        imageView.setImageBitmap(scaledBitmap);


        // 图片压缩
        File storageDirectory = Environment.getExternalStorageDirectory();
//        File[] files = storageDirectory.listFiles();
//        forDir(storageDirectory);

    }

    private void printBmpInfo (Bitmap bitmap) {
        // 获取一下图片的大小
        String size = bitmap.getByteCount() / 1024f / 1024f + "M";
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Log.d("MainActivity", "图片的大小: " + size);
        Log.d("MainActivity", "width:" + width);
        Log.d("MainActivity", "height:" + height);
    }

    private void forDir(File dir){
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                forDir(file);
            }else{
                String path = file.getAbsolutePath().toLowerCase();
                if (path.endsWith(".jpg") || path.endsWith(".jpeg")){
                    Log.d("MainActivity", path);
                }
            }
        }
    }

}
